package com.promise.jokerdream.ui.account

import android.content.Context
import android.util.Log
import com.promise.jokerdream.database.UserDataManager
import com.promise.jokerdream.database.account.UserAccount
import com.promise.jokerdream.config.user.UserConfig
import com.promise.jokerdream.user.UserInfoManager

/**
 * 登录处理器
 * 负责处理用户登录检测和账号管理逻辑
 */
class LoginHandler(
    private val context: Context,
    private val onAccountUpdated: (UserAccount) -> Unit
) {
    
    private val userDataManager = UserDataManager.getInstance(context)
    
    /**
     * 处理登录检测
     * @param userId 用户ID
     * @param username 用户名
     * @param cookie 用户Cookie
     */
    fun handleLoginDetected(userId: String, username: String, cookie: String) {
        val existingAccount = userDataManager.getUserAccount(userId)
        
        if (existingAccount == null) {
            handleNewAccount(userId, username, cookie)
        } else {
            handleExistingAccount(existingAccount, username, cookie)
        }
    }
    
    /**
     * 处理新账号
     */
    private fun handleNewAccount(userId: String, username: String, cookie: String) {
        val newAccount = UserAccount(
            userId = userId,
            username = username,
            cookie = cookie,
            config = UserConfig()
        )
        
        userDataManager.saveUserAccount(newAccount)
        userDataManager.setCurrentAccount(newAccount.userId)
        onAccountUpdated(newAccount)
        
        // 获取用户详细信息
        fetchUserInfo(userId, cookie, newAccount)
        
        Log.d("LoginHandler", "新账号已保存: $username")
    }
    
    /**
     * 处理已存在的账号
     */
    private fun handleExistingAccount(existingAccount: UserAccount, username: String, cookie: String) {
        if (existingAccount.cookie != cookie) {
            // Cookie有变化，更新账号信息
            val updatedAccount = existingAccount.copy(
                username = username,
                cookie = cookie
            )
            userDataManager.saveUserAccount(updatedAccount)
            userDataManager.setCurrentAccount(updatedAccount.userId)
            onAccountUpdated(updatedAccount)
            
            // 获取用户详细信息
            fetchUserInfo(existingAccount.userId, cookie, updatedAccount)
            
            Log.d("LoginHandler", "账号Cookie已更新: $username")
        } else {
            // 相同账号，设置为当前账号
            userDataManager.setCurrentAccount(existingAccount.userId)
            onAccountUpdated(existingAccount)
            
            Log.d("LoginHandler", "切换到已存在账号: $username")
        }
    }
    
    /**
     * 获取用户详细信息
     */
    private fun fetchUserInfo(userId: String, cookie: String, account: UserAccount) {
        UserInfoManager.getUserInfo(
            puin = userId,
            cookie = cookie,
            onSuccess = { userInfo ->
                val updatedAccount = account.copy(
                    username = userInfo.nickname
                )
                userDataManager.saveUserAccount(updatedAccount)
                onAccountUpdated(updatedAccount)
                
                Log.d("LoginHandler", "用户信息已更新: ${userInfo.nickname}")
            },
            onError = { error ->
                Log.e("LoginHandler", "获取用户信息失败: $error")
            }
        )
    }
}
